package com.iwat.mail.util;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.boot.autoconfigure.mail.MailProperties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;


/**
 * @author zhangtao
 * @date 2023-12-26
 * 发送邮件工具类
 */
public class SendMailUtil {
    /**
     * 发送邮件
     * @param receiveMailAccount 收件人
     * @param messageContent 邮件内容
     * @throws Exception 异常
     */
    public static void sendMail(String receiveMailAccount, String messageContent) throws Exception {
        MailProperties mailProperties = SpringUtil.getBean(MailProperties.class);
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", mailProperties.getHost());
        props.setProperty("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props);
        MimeMessage message = createMimeMessage(session, mailProperties.getUsername(), receiveMailAccount,messageContent);
        Transport transport = session.getTransport();
        transport.connect(mailProperties.getUsername(), mailProperties.getPassword());
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     *  创建邮件
     * @param session 绘画
     * @param sendMail 发送人
     * @param receiveMail 收件人
     * @param messageContent 内容
     * @return MimeMessage
     * @throws Exception 异常
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String messageContent) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sendMail, "编码中心", "UTF-8"));
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "编码中心", "UTF-8"));
        message.setSubject("编码中心日志备份通知", "UTF-8");
        message.setSentDate(new Date());
        message.setContent(messageContent, "text/html;charset=UTF-8");
        message.saveChanges();
        return message;
    }

}
